import numpy as np
import pandas as pd

from rectify.get_address_by_id import get_address_by_id


def dzty_mp(df, search_column1, update_column1, search_column2):

    try:
        # 读取Excel文件
        df.replace(np.nan, "", inplace=True)  # 将NaN替换为None
        # 遍历每一行
        for index, row in df.iterrows():
            c1 = str(row[search_column1])  # 户籍详细地址
            c2 = str(row[update_column1])  # 居住地址
            c3 = str(row[search_column2])  # 身份证号

            if any(char.isdigit() for char in str(c1)):
                print("户籍详细地址:", c1)
                segments = c2.split()
                print("居住地址中填写的字段数量:", len(segments))
                if len(segments) >= 6:
                    sixth_segment = segments[5]
                    print("原居住详细地址:", sixth_segment)
                    if not any(char.isdigit() for char in str(sixth_segment)):
                        segments[5] = c1
                        # 将修改后的列表重新组合为字符串
                        new_c2 = ' '.join(segments)
                        print("替换后的居住地址", new_c2)
                        df.at[index, update_column1] = f"{new_c2}"

            segments = c2.split()
            print("居住地址中填写的字段数量:", len(segments))
            # if len(segments) >= 6:
            #     sixth_segment = segments[5]
            #     print("原居住详细地址:", sixth_segment)
            #     if any(char.isdigit() for char in str(sixth_segment)):
            #         if not any(char.isdigit() for char in str(c1)):
            #             print("替换后的户籍详细地址", sixth_segment)
            #             df.at[index, search_column1] = f"{sixth_segment}"
            if len(segments) >= 6:
                sixth_segment = segments[5]
                print("原居住详细地址:", sixth_segment)
                if not any(char.isdigit() for char in str(sixth_segment)):
                    segments[5] = c1
                    # 将修改后的列表重新组合为字符串，确保所有元素都转换为字符串类型
                    new_c2 = ' '.join(map(str, segments))
                    print("替换后的居住地址", new_c2)
                    df.at[index, update_column1] = f"{new_c2}"

        # 保存更新后的Excel文件
        print("[居住地址门牌号]已完成处理。")
        return df
    except Exception as e:
        print(f"居住地址门牌号处理时发生错误：{e}")
